<?php

class Model_Cfg_SearchPage extends Jwawa_BaseModel
{
    protected static $validators = array(
        'id' => array(
            'rules' => array('Int' => null),
            'require' => true,
            'for' => array('update')
        ),
        'entity_header_id' => array(
            'rules' => array('Int' => null)
        ),
        'action_id' => array(
            'rules' => array('Int' => null)
        ),
        'page_name' => array(
            'rules' => array(
                'StringLength' => array('max' => 50)
            ),
            'require' => true
        ),
        'page_code' => array(
            'rules' => array(
                'StringLength' => array('max' => 100)
            ),
            'require' => true
        ),
        'create_by' => array(
            'rules' => array(
                'StringLength' => array('min' => 1,'max' => 10)
            ),
            'require' => true,
            'for' => array('create')
        ),
        'update_by' => array(
            'rules' => array(
                'StringLength' => array('min' => 1,'max' => 10)
            ),
            'require' => true
        ),
        'create_time' => array(
            'rules' => array(
                'Date' => array(
                    'format' => 'yyyy-MM-dd HH:mm:ss'
                )
            ),
            'require' => true,
            'for' => array('create')
        ),
        'update_time' => array(
            'rules' => array(
                'Date' => array(
                    'format' => 'yyyy-MM-dd HH:mm:ss'
                )
            ),
            'require' => true
        ),
        'is_deleted' =>  array(
            'rules' => array(
                'InArray' => array('Y', 'N')
            ),
            'require' => true
        ),
    );

    function __construct(&$prop_array = null)
    {
        parent::__construct($prop_array);

        if($this->entity_header_id === 0){
            $this->entity_header_id = null;
        }
    }

    public static function delPageByIds($ids){
        if(!$ids || count($ids) == 0){
            throw new Jwawa_BusinessException("OBJECT_ID_INVALID", "SearchPage");
        }

        $inIdStr = implode(',', $ids);
        $sql = "UPDATE cfg_search_pages
                SET is_deleted = 'Y'
                WHERE id in ($inIdStr)";

        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->execute();
    }

    public static function getPageById($id){
        if(empty($id)){
            throw new Jwawa_BusinessException("OBJECT_ID_INVALID", ["SearchPage"]);
        }

        $sql = "SELECT  id,
                        entity_header_id,
                        action_id,
                        page_name,
                        page_code,
                        create_time,
                        update_time,
                        create_by,
                        update_by
                FROM cfg_search_pages
                WHERE cfg_search_pages.id = :id
                  AND cfg_search_pages.is_deleted = 'N'";

        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->bindValue('id', $id);
        $stmt->execute();
        $searchPage = $stmt->fetchObj('Model_Cfg_SearchPage');
        if(!$searchPage){
            throw new Jwawa_BusinessException('SEARCH_PAGE_NOT_FOUND', array($id));
        }
        return $searchPage;
    }

    public static function saveOrUpdateSearchPage($searchPage){
        if(empty($searchPage->id)){
            $searchPage = self::saveSearchPage($searchPage);
        } else {
            $searchPage = self::updateSearchPage($searchPage);
        }

        return $searchPage;
    }

    private static function validateUniquePageName($searchPage){
        $sql = "SELECT count(*) c FROM cfg_search_pages
                WHERE is_deleted = 'N' AND page_name = :page_name";
        if($searchPage->id){
            $sql .= ' AND id != :id';
        }
        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->setProperties($searchPage);
        $stmt->execute();
        $rst = $stmt->fetchObj();

        if($rst->c != 0){
            throw new Jwawa_BusinessException("PAGE_NAME_NOT_UNIQUE");
        }
    }

    private static function validateUniquePageCode($searchPage){
        $sql = "SELECT count(*) c FROM cfg_search_pages
                WHERE is_deleted = 'N' AND page_code = :page_code";
        if($searchPage->id){
            $sql .= ' AND id != :id';
        }
        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->setProperties($searchPage);
        $stmt->execute();
        $rst = $stmt->fetchObj();

        if($rst->c != 0){
            throw new Jwawa_BusinessException("PAGE_CODE_NOT_UNIQUE");
        }
    }

    public static function saveSearchPage($searchPage){
        Jwawa_Validate_Factory::validate(self::$validators, $searchPage);
        self::validateUniquePageName($searchPage);
        self::validateUniquePageCode($searchPage);

        $sql = 'INSERT INTO cfg_search_pages (page_name, page_code, entity_header_id, action_id, create_time, update_time, create_by, update_by, is_deleted)
                VALUES (:page_name, :page_code, :entity_header_id, :action_id, :create_time, :update_time, :create_by, :update_by, :is_deleted)';
        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->setProperties($searchPage);

        if($rst = $stmt->execute()){
            $id = self::getDb()->lastInsertId();
            $searchPage->id = $id;
            return $searchPage;
        } else {
            return null;
        }
    }

    public static function updateSearchPage($searchPage){
        Jwawa_Validate_Factory::validate(self::$validators, $searchPage, 'update');
        self::validateUniquePageName($searchPage);
        self::validateUniquePageCode($searchPage);

        $sql = "UPDATE cfg_search_pages
                SET page_name = :page_name,
                    page_code = :page_code,
                    entity_header_id = :entity_header_id,
                    action_id = :action_id,
                    update_time = :update_time,
                    update_by = :update_by,
                    is_deleted = 'N'
                WHERE id = :id";
        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->setProperties($searchPage);
        $stmt->execute();
        return $searchPage;
    }

    public static function countPageListBySbr($sbr){
        $sql = "SELECT count(*) c
                FROM cfg_search_pages
                WHERE is_deleted = 'N' ";
        $sql .= $sbr->build(true);


//        if(!empty($queryDto['page_name'])){
////            $sql .= ' AND page_name like %' . $queryDto['page_name'] . '%';
//            $sql .= sprintf( " AND page_name like '%%%s%%'", $queryDto['page_name']);
//        }
//        if(!empty($queryDto['page_code'])){
//            $sql .= ' AND page_code = :page_code';
//        }
//        if(!empty($queryDto['create_time_from'])){
//            $sql .= ' AND create_time >= :create_time_from';
//        }
//        if(!empty($queryDto['create_time_to'])){
//            $sql .= ' AND create_time <= :create_time_to';
//        }

        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->setProperties($sbr->getSearchItems());
        $stmt->execute();
        $rst = $stmt->fetchObj();

        return $rst->c;
    }

    public static function findPageListBySbr($sbr){
        $sql = "SELECT id,
                       page_name,
                       page_code
                FROM cfg_search_pages
                WHERE is_deleted = 'N'";
        $sql .= $sbr->build();

//        if(!empty($queryDto['page_name'])){
////            $sql .= ' AND page_name like %' . $queryDto['page_name'] . '%';
//            $sql .= sprintf( " AND page_name like '%%%s%%'", $queryDto['page_name']);
//        }
//        if(!empty($queryDto['page_code'])){
//            $sql .= ' AND page_code = :page_code';
//        }
//        if(!empty($queryDto['create_time_from'])){
//            $sql .= ' AND create_time >= :create_time_from';
//        }
//        if(!empty($queryDto['create_time_to'])){
//            $sql .= ' AND create_time <= :create_time_to';
//        }
//
//        if(is_numeric($queryDto['start']) and is_numeric($queryDto['limit'])){
//            $sql .= sprintf(' LIMIT %d, %d', $queryDto['start'], $queryDto['limit']);
//        }

        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->setProperties($sbr->getSearchItems());
        $stmt->execute();
        $rst = $stmt->fetchAllObj();

        return $rst;
    }

    public static function getPageIdByCode($pageCode){
        $sql = "SELECT id
                FROM cfg_search_pages csp
                WHERE	csp.page_code = :page_code
                AND csp.is_deleted = 'N'";

        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->bindValue('page_code', $pageCode);
        $stmt->execute();
        $rst = $stmt->fetchObj();

        return $rst->id;
    }

    public static function getPageCodeById($id){
        $sql = "SELECT page_code
                FROM cfg_search_pages csp
                WHERE	csp.id = :id
                AND csp.is_deleted = 'N'";

        $stmt = self::createDefaultStmt(self::getDb(), $sql);
        $stmt->bindValue('id', $id);
        $stmt->execute();
        $rst = $stmt->fetchObj();

        return $rst->page_code;
    }
}
